package uk.co.aetherworks.serial_osc;

/*
 * Ped-ome
 *
 * SerialOSCListener - Listens for SerialOSC devices
 *
 * Joe Handford aka Knecht 2011 derived from code by Phortran
 *
 */ 

// Bonjour Include Files
import com.apple.dnssd.*;

// aetherworks imports
import uk.co.aetherworks.active_devices.*;
import uk.co.aetherworks.debug.*;
 
public class SerialOSCListener extends Debuggable implements BrowseListener, ResolveListener {

	ActiveDevices detectedDevices;
	ActiveDevicePublisher publisher;
//	ArrayList<DNSSDService> dnssdServices;

	public SerialOSCListener(ActiveDevices devices, ActiveDevicePublisher aPublisher) {
		detectedDevices = devices;
		publisher = aPublisher;
//		dnssdServices = new ArrayList<DNSSDService>();
	}
	
	public void operationFailed(DNSSDService arg0, int arg1) {
		System.out.println("Operation failed: " + arg0 + " [" + arg1 + "]");
	}
	
	public void serviceLost(DNSSDService arg0, int arg1, int arg2, String arg3, String arg4, String arg5) {
		System.out.println("Service Lost: [" + arg3 + "] [" + arg4 + "] [" + arg5 + "]");
	}

	public void serviceFound(DNSSDService browser, int flags, int index, String serviceName, String regType, String domain) {
		DEBUG(serviceName + " found");
		try {
			DNSSDService service = DNSSD.resolve(0, DNSSD.ALL_INTERFACES, serviceName, regType, domain, this);
//			dnssdServices.add(service);
		} catch (DNSSDException e) {
			e.printStackTrace();
		}
	}

	public synchronized void serviceResolved(DNSSDService resolver, int flags, int ifIndex, String fullName, String hostName, int port, TXTRecord txtRecord) {
		// Only process service if not pedome service
		if (fullName.indexOf("pedome") == -1) {
			String serial = fullName.substring(0, fullName.indexOf("._"));
			int delim_pos = fullName.indexOf(".");
			String deviceName = fullName.substring(0,delim_pos);
			detectedDevices.addDevice(deviceName, port);
			detectedDevices.printDevices();
			publisher.publishDevices(detectedDevices);
		}
	}
	
//	public void stopDNSSDServices() {
//		for (DNSSDService service : dnssdServices) {
//			service.stop();
//		}
//	}
}
